package com.kedacom.freedomLabel.viewmodel;


import android.arch.lifecycle.MutableLiveData;
import android.support.annotation.Nullable;

import com.kedacom.freedomLabel.base.BaseViewModel;
import com.kedacom.freedomLabel.model.bean.IFirstLetter;
import com.kedacom.freedomLabel.model.db.DataCallback;
import com.kedacom.freedomLabel.model.db.DataLoader;
import com.kedacom.freedomLabel.model.db.dao.IDao;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ListDataViewModel<T extends IFirstLetter> extends BaseViewModel {

    private MutableLiveData<List<T>> mLiveData = new MutableLiveData<>();
    public List<T> mDataList = new ArrayList<>();

    public MutableLiveData<List<T>> getDataLiveData() {
        return mLiveData;
    }

    public ListDataViewModel() {
    }

    public void getDataList(IDao<T> dao, String param1, String param2) {
        if (param1 != null && param2 != null) {
            DataLoader.get(dao, param1, param2, new DataCallback<List<T>>() {
                @Override
                public void success(@Nullable List<T> data) {
                    postData(data);
                }

                @Override
                public void error(@Nullable String errorMessage) {
                    postData(null);
                }
            });
        } else if (param1 != null) {
            DataLoader.get(dao, param1, new DataCallback<List<T>>() {
                @Override
                public void success(@Nullable List<T> data) {
                    postData(data);
                }

                @Override
                public void error(@Nullable String errorMessage) {
                    postData(null);
                }
            });
        } else if (param2 != null) {
            DataLoader.get(dao, param2, new DataCallback<List<T>>() {
                @Override
                public void success(@Nullable List<T> data) {
                    postData(data);
                }

                @Override
                public void error(@Nullable String errorMessage) {
                    postData(null);
                }
            });
        } else {
            DataLoader.get(dao, new DataCallback<List<T>>() {
                @Override
                public void success(@Nullable List<T> data) {
                    postData(data);
                }

                @Override
                public void error(@Nullable String errorMessage) {
                    postData(null);
                }
            });
        }
    }

    private void postData(@Nullable List<T> data) {
        mDataList.clear();
        if (data != null) {
            Collections.sort(data);
            mDataList.addAll(data);
        }
        mLiveData.setValue(mDataList);
    }
}